<?php

declare(strict_types=1);

namespace DreamCat\ObjectValid\Annotation;

use Attribute;
use DreamCat\ObjectValid\Base\ValidAnnoInterface;
use DreamCat\ObjectValid\Utils\ReflectionUtils;
use JetBrains\PhpStorm\Immutable;
use ReflectionParameter;
use ReflectionProperty;

/**
 * 对字符串的正则限制
 * @author vijay
 */
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER | Attribute::IS_REPEATABLE)]
#[Immutable]
class Pattern implements ValidAnnoInterface
{
    /**
     * @param string $pattern 限制的正则
     * @param string|null $message 错误信息
     */
    public function __construct(private string $pattern, private ?string $message = null)
    {
    }

    /**
     * @return string 限制的正则
     */
    public function getPattern(): string
    {
        return $this->pattern;
    }

    /**
     * @return string|null 错误信息
     */
    public function getMessage(): ?string
    {
        return $this->message;
    }

    /**
     * @inheritDoc
     */
    public function errorMessage(ReflectionParameter|ReflectionProperty $reflection, mixed $value): string
    {
        if (!is_null($this->message)) {
            return $this->message;
        }
        return ReflectionUtils::getReflectDesc($reflection) . " 不匹配要求的正则表达式 {$this->pattern}";
    }

    /**
     * @inheritDoc
     */
    public function isValid(mixed $value): bool
    {
        if ($value === null) {
            return true;
        }
        return boolval(preg_match($this->pattern, strval($value)));
    }
}

# end of file
